/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import java.util.List;
import models.Category;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 *
 * @author Vuong Pham<Vuong.Pham@hva.nl>
 */
public class CategoryDao {

    private final Session session;

    /*
     * Constructor with session parameter
     */
    public CategoryDao(Session session) {
        this.session = session;
    }

    /*
     * Returns a list of all the categories
     */
    public List<Category> findAll() {
        Transaction tx = session.beginTransaction();
        List<Category> list = session.createQuery("from Category as c ORDER BY c.name ASC").list();
        tx.commit();
        return list;
    }

    /*
     * Saves a category in the database
     * 
     */
    public boolean save(Category category) {
        try {
            Transaction tx = session.beginTransaction();
            session.save(category);
            tx.commit();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /*
     * Updates a category object
     */
    public boolean update(Category category) {
        try {
            Transaction tx = session.beginTransaction();
            session.update(category);
            tx.commit();
            return true;
        } catch (Exception e) {
            // System.out.println("Error during update: " + e);
            return false;
        }
    }

    /*
     * Returns a category.
     */
    public Category get(long id) {
        return (Category) session.get(Category.class, id);
    }

    /*
     * Deletes a category.
     */
    public void delete(Category category) {
        Transaction tx = session.beginTransaction();
        session.delete(category);
        tx.commit();
    }
}
